package com.twu.biblioteca;

import java.io.IOException;

/**
 * Created by olga on 7/06/14.
 */
public class BibliotecaRunner
{
    private static final String OPTION_PROMPT = "Please enter an option number: ";
    private static final String UNABLE_TO_READ_OPTION_PROMPT = "Something went wrong - unable to read entered options.";

    public void run()
    {
        TerminalPrintUtility.printWelcomeMessage();
        initialiseComponents();

        mainLoop();

        TerminalPrintUtility.printExitMessage();
    }

    /* Not quite sure how to test this one... */
    public void mainLoop()
    {
        boolean quit = false;
        while( !quit )
        {
            Menu.getInstance().printMenu();

            String userOption = readUserInput();
            if( userOption == null )
                break;

            quit = Menu.getInstance().processUserAction(userOption.trim());
        }
    }

    public String readUserInput()
    {
        String userOption = "";
        try
        {
            userOption = TerminalReadUtility.getUserInput(OPTION_PROMPT);
        }
        catch( IOException e )
        {
            TerminalPrintUtility.printStringWithCarriageReturn(UNABLE_TO_READ_OPTION_PROMPT);
            return null;
        }

        return userOption.trim();
    }

    private void initialiseComponents()
    {
        LibraryManager library = LibraryManager.initialiseBookLibrary();
        Menu.getInstance().setLibraryManager(library);
    }
}
